package com.kuaimacode.kframework.weixin;


import com.alibaba.fastjson.JSONObject;
import com.kuaimacode.kframework.util.AES;
import org.apache.commons.codec.binary.Base64;

/**
 * @author qinyong
 * @Title: 封装对外访问方法
 * @Package com.kuaimacode.kframework.weixin
 * @Description: created by IntelliJ IDEA
 * @date 2019-07-19 10:23
 */
public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws Exception{
        String appId = "wxcb62fb96acbf55cb";
        String encryptedData = "TwVMidlBj1d0eI53EuLkMAjiXxhON3hKUp4EQuSyA10dUO8qCawyjQfxCve5gV7sDou+qUOgRBWmXsVsuJBL42Qef5MWVT/eQYOJrwFAX+Fpc75DuBUdRzzvF/AJQruR5tfv1CBI68K0CNQMJi5TXyuJFPEXggxV2ly0TSw+jnGwGWrAHWD3K+YUk8ypCgRBxO0zwWxMvpYMga6XXKLlKQ==";
        String sessionKey = "lOdSNpuvCy2JadNuTgeByg==";
        String iv = "XuDQrU1mnOWqemgj8IbZLQ==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }
}
